package com.qf.ability.notify.service.impl;

import com.qf.ability.notify.service.IEmailNotifyService;
import com.qf.data.notify.entity.Email;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

/**
 * author Ken
 * create_time 2022/11/24
 */
@Service
@Slf4j
public class EmailNotifyServiceImpl implements IEmailNotifyService {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送邮件的业务
     * @param email
     * @return
     */
    @Override
    public int sendEmail(Email email) {
        log.debug("[send email] 执行发送邮件的业务 - {}", email);

        //创建一封邮件
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        //使用Spring的对象 对邮件进行二次封装
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
        try {
            //设置标题
            mimeMessageHelper.setSubject(email.getSubject());

            //设置发送方
            mimeMessageHelper.setFrom(from);

            //设置接收方
            mimeMessageHelper.setTo(email.getTos().toArray(new String[0]));

            //发送时间
            mimeMessageHelper.setSentDate(new Date());

            //发送的内容
            mimeMessageHelper.setText(email.getContent());

            //发送邮件
            mailSender.send(mimeMessage);
            return 1;
        } catch (MessagingException e) {
            log.error("[send email error] 发送邮件异常！", e);
        }

        return 0;
    }
}
